
class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;
    }
}


/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Lily
 * Date: 2024-11-08
 * Time: 20:58
 */
public class test_1 {
    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     *
     * @param pRoot TreeNode类
     * @return bool布尔型
     */
    public boolean IsBalanced_Solution(TreeNode pRoot) {
        return dfs(pRoot) != -1;
    }

    public int dfs(TreeNode root) { // 当返回值不是 -1 的时候，返回的是树的⾼度 {
        if (root == null) return 0;
        int left = dfs(root.left);
        if (left == -1) return -1; // 剪枝
        int right = dfs(root.right);
        if (right == -1) return -1; // 剪枝
        return Math.abs(left - right) <= 1 ? Math.max(left, right) + 1 : -1;
    }
}
